// overlay.js（完整代码）
// 监听来自背景脚本的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'showOverlay') {
    console.log('收到显示遮罩层消息，URL:', message.url, '发送者:', sender.url);
    
    // 严格检查是否为主框架，包括sender信息验证
    if (window.top !== window.self || 
        (sender.tab && sender.frameId !== 0)) {
      console.log('iframe中不显示遮罩层，来源:', sender.url, 'frameId:', sender.frameId);
      return;
    }
    
    // 如果已经有遮罩层，先移除
    const existingOverlay = document.getElementById('focus-assistant-overlay');
    if (existingOverlay) {
      document.body.removeChild(existingOverlay);
    }
    
    // 创建遮罩层元素
    const overlay = document.createElement('div');
    overlay.id = 'focus-assistant-overlay';
    
    // 提取域名和路径显示
    let displayUrl = message.url;
    try {
      const urlObj = new URL(message.url);
      displayUrl = `${urlObj.hostname}${urlObj.pathname}`;
    } catch (e) {
      console.error('解析URL失败:', e);
    }
    
    // 设置遮罩层样式和内容
    overlay.innerHTML = `
      <style>
        #focus-assistant-overlay {
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.85);
          z-index: 9999;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          color: white;
          font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, sans-serif;
          text-align: center;
          padding: 20px;
          box-sizing: border-box;
          animation: fadeIn 0.3s ease-out;
        }
        
        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        
        .overlay-container {
          max-width: 600px;
          width: 100%;
          padding: 40px;
          background-color: rgba(255, 255, 255, 0.05);
          border-radius: 16px;
          backdrop-filter: blur(10px);
          box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        }
        
        .overlay-title {
          font-size: 28px;
          font-weight: 600;
          margin-bottom: 20px;
          color: #fff;
          text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }
        
        .overlay-message {
          font-size: 18px;
          margin-bottom: 30px;
          color: #eee;
          line-height: 1.5;
        }
        
        .overlay-url {
          font-size: 16px;
          background-color: rgba(255, 255, 255, 0.1);
          padding: 12px 18px;
          border-radius: 8px;
          margin-bottom: 40px;
          max-width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-family: monospace;
          color: #a8dadc;
        }
        
        .overlay-buttons {
          display: flex;
          gap: 15px;
          justify-content: center;
        }
        
        .overlay-button {
          padding: 12px 28px;
          border: none;
          border-radius: 8px;
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          transition: all 0.3s ease;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }
        
        .overlay-allow {
          background-color: #4361ee;
          color: white;
        }
        
        .overlay-allow:hover {
          background-color: #3a0ca3;
          transform: translateY(-2px);
          box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);
        }
        
        .overlay-block {
          background-color: rgba(255, 255, 255, 0.1);
          color: white;
          border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .overlay-block:hover {
          background-color: rgba(255, 255, 255, 0.2);
          transform: translateY(-2px);
          box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);
        }
      </style>
      <div class="overlay-container">
        <div class="overlay-title">专注助手</div>
        <div class="overlay-message">您正在访问的网站未在允许列表中</div>
        <div class="overlay-url">${displayUrl}</div>
        <div class="overlay-buttons">
          <button class="overlay-block" id="focus-assistant-block">返回</button>
        </div>
      </div>
    `;
    
    // 添加到页面
    document.body.appendChild(overlay);
    
    // 添加按钮事件监听 TODO // <button class="overlay-allow" id="focus-assistant-allow">允许访问</button>
    // document.getElementById('focus-assistant-allow').addEventListener('click', () => {
    //   // 获取当前标签ID
    //   chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
    //     if (tabs.length) {
    //       const tabId = tabs[0].id;
          
    //       // 发送消息到背景脚本添加当前URL到允许列表
    //       chrome.runtime.sendMessage({
    //         action: 'addCurrentUrlToAllowed',
    //         url: message.url,
    //         tabId
    //       }, response => {
    //         if (response && response.success) {
    //           console.log('已添加到允许列表:', response.pattern);
    //           showStatus('已允许访问此网站', 'success');
    //         } else {
    //           console.error('添加到允许列表失败');
    //           showStatus('添加失败，请重试', 'error');
    //         }
            
    //         // 移除遮罩层
    //         document.body.removeChild(overlay);
    //       });
    //     }
    //   });
    // });
    
    document.getElementById('focus-assistant-block').addEventListener('click', () => {
      // 返回上一页
      if (window.history.length > 1) {
        window.history.back();
      } else {
        // 如果没有上一页，关闭标签页
        chrome.runtime.sendMessage({ action: 'closeTab' });
      }
      
      // 移除遮罩层
      document.body.removeChild(overlay);
    });
    
    // 显示状态消息函数
    function showStatus(message, type) {
      const statusDiv = document.createElement('div');
      statusDiv.className = `focus-assistant-status ${type}`;
      statusDiv.textContent = message;
      
      document.body.appendChild(statusDiv);
      
      setTimeout(() => {
        statusDiv.style.opacity = '0';
        setTimeout(() => {
          document.body.removeChild(statusDiv);
        }, 300);
      }, 2000);
    }
  }
});

// 页面加载时主动检查当前URL是否需要拦截
document.addEventListener('DOMContentLoaded', async () => {
  try {
    // 只在主框架中检查
    if (window.top !== window.self) {
      console.log('iframe中不执行URL检查');
      return;
    }
    
    const currentUrl = window.location.href;
    
    // 获取当前标签ID
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tab) return;
    
    // 从存储中获取允许的域名列表
    chrome.storage.sync.get(['allowedDomains'], ({ allowedDomains }) => {
      // 检查当前URL是否在允许列表中
      const isAllowed = allowedDomains?.some(pattern => {
        const regexPattern = pattern
          .replace(/\./g, '\\.')
          .replace(/\*/g, '.*')
          .replace(/\//g, '\\/');
        return new RegExp(`^${regexPattern}$`).test(currentUrl);
      });
      
      // 检查是否已被标记为拦截
      chrome.storage.local.get([`blocked_${tab.id}`], (result) => {
        const isBlocked = result[`blocked_${tab.id}`] === currentUrl;
        
        // 如果不在允许列表中且未被记录，则主动触发拦截
        if (!isAllowed && !isBlocked) {
          console.log('主动触发拦截:', currentUrl);
          
          // 发送消息到背景脚本记录拦截
          chrome.runtime.sendMessage({
            action: 'recordBlockedUrl',
            tabId: tab.id,
            url: currentUrl
          });
          
          // 创建并显示遮罩层
          const overlay = document.createElement('div');
          overlay.id = 'focus-assistant-overlay';
          
          // 提取域名显示
          let displayUrl = currentUrl;
          try {
            const urlObj = new URL(currentUrl);
            displayUrl = urlObj.hostname + urlObj.pathname;
          } catch (e) {
            console.error('解析URL失败:', e);
          }
          
          // 设置遮罩层样式和内容
          overlay.innerHTML = `
            <style>
              /* 与上面相同的样式... */
            </style>
            <div class="overlay-container">
              <div class="overlay-title">专注助手</div>
              <div class="overlay-message">您正在访问的网站未在允许列表中</div>
              <div class="overlay-url">${displayUrl}</div>
              <div class="overlay-buttons">
                <button class="overlay-allow" id="focus-assistant-allow">允许访问</button>
                <button class="overlay-block" id="focus-assistant-block">返回</button>
              </div>
            </div>
          `;
          
          document.body.appendChild(overlay);
          
          // 添加按钮事件监听
          document.getElementById('focus-assistant-allow').addEventListener('click', () => {
            chrome.runtime.sendMessage({
              action: 'addCurrentUrlToAllowed',
              url: currentUrl,
              tabId: tab.id
            });
            
            // 移除遮罩层并清除存储
            chrome.storage.local.remove(`blocked_${tab.id}`);
            document.body.removeChild(overlay);
          });
          
          document.getElementById('focus-assistant-block').addEventListener('click', () => {
            if (window.history.length > 1) {
              window.history.back();
            } else {
              chrome.runtime.sendMessage({ action: 'closeTab' });
            }
            
            chrome.storage.local.remove(`blocked_${tab.id}`);
            document.body.removeChild(overlay);
          });
        } else if (!isAllowed && isBlocked) {
          // 如果已被标记为拦截，直接显示遮罩层（不重复记录）
          console.log('恢复拦截状态:', currentUrl);
          
          // 创建并显示遮罩层（代码同上）
          const overlay = document.createElement('div');
          overlay.id = 'focus-assistant-overlay';
          // ...（遮罩层HTML代码同上）
          
          document.body.appendChild(overlay);
          // ...（按钮事件监听代码同上）
        }
      });
    });
  } catch (e) {
    console.error('页面加载时检查URL失败:', e);
  }
});